package net.roobook.auth.service;

import net.roobook.common.entity.RoobookAuthUser;
import net.roobook.common.entity.system.SysUser;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * @Author Roobook
 * @description 用于校验用户名密码的类
 * @date 2022/4/7
 */
@Service
public class RoobookUserDetailService  implements UserDetailsService {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //从数据库中获取用户信息SysUser
        SysUser sysUser = userService.findByName(username);

        if (sysUser != null) {
            //从数据库中获取用户权限集合
            String permissions = userService.findUserPermissions(sysUser.getUsername());
            boolean notLocked = false;
            if (StringUtils.equals(SysUser.STATUS_VALID, sysUser.getStatus()))
                notLocked = true;
            RoobookAuthUser authUser = new RoobookAuthUser(sysUser.getUsername(), sysUser.getPassword(), true, true, true, notLocked,
                    AuthorityUtils.commaSeparatedStringToAuthorityList(permissions));
            //拷贝
            BeanUtils.copyProperties(sysUser,authUser);
            return authUser;
        } else {
            throw new UsernameNotFoundException("");
        }
    }
}
